<template>
	<view>
		<!-- <u-navbar leftIcon="list-dot" title="路线" @leftClick="leftClick" ></u-navbar> -->
		<!-- #ifdef APP-PLUS || H5 -->
		<view class="map-wrap">
			<view id="toast"></view>
			<view id="control-legend">
				<view class="control-legend-content">
					<view class="title">图例</view>
					<img src="https://p1.qhimg.com/t017d95fed2028c750e.png" alt="" />
				</view>
			</view>
			<view id="basemap-switch-panel">
				<view class="title">选择底图</view>
				<view class="basemap-container">
					<view class="basemap-item active" id="vec-basemap-button" name="vec">
						<image class="thumbnail" src="/static/tuli/vec.jpg"></image>
						<view>矢量底图</view>
					</view>
					<view class="basemap-item" id="img-basemap-button" name="img">
						<image class="thumbnail" src="/static/tuli/raster.jpg"></image>
						<view>影像底图</view>
					</view>
				</view>
			</view>
			<view id="button-cancel-highlight-route">取消线路高亮</view>
			<u-toast ref="uToast"></u-toast>
			<view class="topbar">
				<u-icon class="check-equipment" name="list-dot" size="30" bold @click="leftClick"></u-icon>
				<view class="search-input">
					<u-search class="search" placeholder="查找设备、电缆井、接头" v-model="keyword" :showAction="false"></u-search>
					<view class="search-result" id="search-result" v-show="keyword.length >= 2">
						<view v-if="isEmptyList" class="empty-result">没有搜索结果</view>
						<u-list id="search-result-list" v-else height="300">
							<u-list-item v-for="item in searchResult" :key="item.id">
								<view class="u-list-item-cell" @click="handleListItemClick(item)">{{ item.name }}</view>
							</u-list-item>
						</u-list>
					</view>
				</view>
			</view>

			<view id="map-box" :prop="selectedTreeNode" :change:prop="mapboxModule.locateRoute"><!-- 这里是mapbox的地图容器 -->
			</view>
			<scroll-view id="channel-panel" class="tabs">
				<view class="tab-header">
					<view class="tab-header-item active" id="channel-tab-channel">通道详情</view>
					<view class="tab-header-item" id="channel-tab-cable">电缆段</view>
				</view>
				<view class="panes-container">
					<view class="tab-pane active" id="tab1"></view>
					<view class="tab-pane" id="tab2"></view>
				</view>
			</scroll-view>
			<!-- 电缆井接头 电缆井图标 中间带红色的那个 -->
			<scroll-view id="cable-well-panel" class="tabs">
				<view class="cable-well-panel-title">
					电缆井
					<text class="address">导航</text>
				</view>
				<view class="tab-header">
					<view class="tab-header-item active" id="cable-well-tab-1">电缆井详情</view>
					<view class="tab-header-item" id="cable-well-tab-2">接头</view>
				</view>
				<!-- 从数据库获取电缆井数据 -->
				<view class="panes-container">
					<view class="tab-pane active" id="tab3"></view>
					<view class="tab-pane" id="tab4">
						<view id="connector-list"></view>
						<view class="connector-detail-pane" id="connector-detail-pane">
							<view id="back-to-list">&lt; 返回列表</view>
							<view id="connector-detail"></view>
						</view>
					</view>
				</view>
			</scroll-view>
			<scroll-view class="properties-panel" id="properties-panel">
				<view class="tab-header">
					<view class="tab-header-item" :class="{ active: activeTab === 'cableWell' }"
						@click="switchTab('cableWell')">电缆井详情</view>
					<view class="tab-header-item" :class="{ active: activeTab === 'onlineMonitoring' }"
						@click="switchTab('onlineMonitoring')">在线监测</view>
				</view>
				<view class="panes-container">
					<view class="tab-pane" v-show="activeTab === 'cableWell'" id="tab-cable-well">
						<view>
							<text class="title">电缆井</text>
							<text class="address" id="address">导航信息</text>
						</view>
						<view class="table-container">
							<!-- 这里可以放置电缆井的详细信息 -->
						</view>
					</view>
					<view class="tab-pane" v-show="activeTab === 'onlineMonitoring'" id="tab-empty-content">
						<view class="select-style">
							<text>选择接头：</text>
							<picker :value="projectHead" :range="heads" range-key="name" class="project-picker"
								@change="tashHeadChange">
								<view class="picker-content">
									{{ projectHead ? projectHead : ' 请选择接头' }}
								</view>
							</picker>
						</view>
						<view class="temperature-item-one">
							<view class="row">
								<text class="label">主机状态：</text>
								<text class="value">{{hostData.hostStatus }}</text>
							</view>
							<view class="row">
								<text class="label">水浸状态：</text>
								<text class="value">{{hostData.waterStatus }}</text>
							</view>
						</view>
						<view class="temperature-item">
							<view class="row">
								<text class="label">环境温度：</text>
								<text class="value">{{hostData.environmentTemperature}}</text>
							</view>
							<view class="row">
								<text class="label">接头温度：</text>
								<text class="value">{{hostData.cableTemperature}}</text>
							</view>
						</view>
						<view class="temperature-item">
							<view class="row">
								<text class="label">局放峰值：</text>
								<text class="value">{{hostData.peakValue }}</text>
							</view>
							<view class="row">
								<text class="label">局放均值：</text>
								<text class="value">{{hostData.averageValue}}</text>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>

		</view>
		<nav-bar :value="1"></nav-bar>
		<u-popup :show="showPopup" mode="left" @close="closePopup" @open="openPopup" :safeAreaInsetTop="true">
			<view>
				<ly-tree ref="tree" :tree-data="treeData" :props="tree_props" node-key="id" :showNodeIcon="true"
					:highlightCurrent="true" :ready="ready" @node-expand="handleNodeExpand"
					@node-click="handleNodeClick" :expandOnClickNode="false" :defaultExpandedKeys="defaultExpandedKeys"
					:defaultCheckedKeys="defaultCheckedKeys" :autoExpandParent="true"
					:currentNodeKey="currentNodeKey"></ly-tree>
			</view>
		</u-popup>
		<!-- #endif -->
	</view>
</template>

<script>
	import request from '@/util/request/request.js'
	import navBar from '@/components/common/nav';
	import LyTree from '@/components/ly-tree/ly-tree';
	import loadStaticData from '@/util/loadStaticData.js';
	import _ from 'lodash';
	import {
		selectSql
	} from '@/util/sqliteHelper.js';
	import store from '@/store/index';
	export default {
		components: {
			navBar,
			LyTree
		},
		name: '',
		data() {
			return {
				heads: [], //返回的接头数据再heads中
				projectHead: '',
				hostData: [],
				taskProject: '',
				projects: [], // 存储项目数据
				activeTab: 'cableWell', // 默认显示的选项卡
				map: null, //地图实例
				selectedFeature: null,
				showPopup: false,
				treeData: null,
				tree_props: {
					id: 'id',
					label: 'name',
					children: 'children',
					icon: 'type'
				},
				selectedTreeNode: {},
				keyword: '',
				searchResult: [],
				resultPanelStyle: {
					height: 0
				},
				token: uni.getStorageSync('TOKEN_KEY'),
				defaultExpandedKeys: [],
				defaultCheckedKeys: [],
				currentNodeKey: ''
			};
		},
		async mounted() {
			
		},
		onLoad() {},
		computed: {
			isEmptyList: function() {
				return this.keyword !== '' && this.searchResult.length === 0;
			},
			ready: function() {
				return this.treeData !== null;
			},
			treeStatus() {
				return store.state.treeData;
			}
		},
		methods: {
			tashHeadChange(val) {
				this.projectHead = this.heads[val.detail.value].name
				this.projectHeadId = this.heads[val.detail.value].id
				console.log('选中的接头名称', this.projectHead)
				console.log('选中的接头名称id', this.projectHeadId)
				this.fetchLineData(this.projectHeadId);

			},
			//根据电缆井id去获取接头
			async fetchHeadName(selectedStateId) {
				//id指的是电缆井id
				const apiUrl =
				`http://192.168.2.187:8080/mConnectHost/selectConnectorByHostIds?wellId=${selectedStateId}`;
					// `http://192.168.2.187:8080/mConnectHost/selectConnectorByHostIds?wellId=1410886869720133636`;
					// 1837290576221880321
				console.log('接口已经拿到电缆井id：', this.selectedStateId)
				try {
					const res = await request({
						url: apiUrl,
					});
					if (res.status === 'SUCCESS') {
						this.heads = res.result; //获取的接头在result中
						console.log('获取接头成功，结果为:', res);
					} else {
						console.error('获取接头失败，状态不是 SUCCESS:', res);
					}
				} catch (error) {
					console.error('获取接头失败:', error);
				}
			},
			//根据接头id获取对应的在线监测数据
			async fetchLineData(projectHeadId) {
				//id指的是接头的id
				const apiUrl =
					`http://192.168.2.187:8080/mConnectHost/selectHostByHostNumber?connectId=${this.projectHeadId}`;
					// `http://192.168.2.187:8080/mConnectHost/selectHostByHostNumber?connectId=1410886869720133636`;
				console.log('接口已经拿到选中接头id：', this.projectHeadId)
				try {
					const res = await request({
						url: apiUrl,
					});
					if (res.status === 'SUCCESS') {
						this.hostData = res.result; //获取的接头在result中
						console.log('获取在线监测数据成功，结果为:', res);
					} else {
						console.error('获取在线监测数据失败，状态不是 SUCCESS:', res);
					}
				} catch (error) {
					console.error('获取在线监测失败:', error);
				}
			},


			switchTab(tab) {
				this.activeTab = tab; // 切换选项卡
			},
			leftClick: function() {
				this.showPopup = true;
				this.loadTreeData();
			},
			closePopup: function() {
				this.showPopup = false;
			},
			openPopup: function() {
				this.showPopup = true;
			},
			handleNodeClick(obj) {
				const data = obj.data;
				const {
					id
				} = data;

				if (typeof id !== 'string' || id.length < 16) {
					// 关键数据的id都是19位，短的id都是处理数据过程中自动生成的
					return;
				}
				this.selectedTreeNode = data;
				this.defaultCheckedKeys = [data.id]; // 默认选中节点
				this.currentNodeKey = data.id; // 选中当前节点
				this.closePopup();
			},
			handleNodeExpand(obj) {
				this.defaultExpandedKeys = [obj.data.id]; // 设置默认展开节点
			},
			loadTreeData() {
				// console.log(store.state.treeData.length, '12123123123');
				// if (store.state.treeData.length == 0) {
				// 	store.dispatch('getTreeData');
				// }
				console.log(store.state.treeData.length, '2222222');
				this.treeData = store.state.treeData;
				// loadStaticData('tree_union.json')
				// 	.then(result => {
				// 		console.log('tree-data加载完成');
				// 		this.treeData = [result];
				// 	})
				// 	.catch(e => {
				// 		console.error(e);
				// 	});
			},
			queryInSqlite() {
				return _.throttle(val => {
					return selectSql(`select * from tzinfo where name like %${val}%`).then(res => {
						console.log(res);
						return res;
					});
				}, 500);
			},
			handleListItemClick(item) {
				this.selectedTreeNode = item;
				if (item.id && item.type) {
					this.keyword = '';
				}
			}
		},
		watch: {
			keyword: function(val, oldVal) {
				if (_.isEmpty(val)) {
					this.searchResult = [];
				}
				if (val.length < 2) {
					// 至少输入两个字才开始搜索
					return;
				}

				selectSql(`select id,name,type from tzinfo where name like '%${val}%' limit 20`)
					.then(res => {
						this.searchResult = res;
						return res;
					})
					.catch(e => {
						console.error(e);
					});
			},
			treeStatus: {
				handler(newVal) {
					// console.log(newVal.length, '122');
					this.treeData = newVal;
				},
				deep: true
			}
		},

	};
</script>

<script module="mapboxModule" lang="renderjs">
	import {
		mapState
	} from 'vuex';
	import request from '@/util/request/request.js'
	import {
		openDatabase,
		selectSql,
		isOpenDatabase
	} from '@/util/sqliteHelper.js'
	import legendControl from "./control-legend";
	import basemapSwitchControl, {
		vecBaseMapStyle,
		imgBaseMapStyle
	} from "./control-basemap-switcher";
	import loadStaticData from '@/util/loadStaticData.js'
	import {
		loadBitmap,
		replaceImageColor,
		overlapConnectorIcon
	} from "./icon-helper";
	const mapboxgl = require('!mapbox-gl/dist/mapbox-gl.js');

	let propertiesPanel = null
	let currentBaseMap = 'vec'
	let navigationData = {}

	var link = document.createElement("link");
	link.rel = "stylesheet";
	link.type = "text/css";
	link.href = "https://api.mapbox.com/mapbox-gl-js/v2.10.0/mapbox-gl.css";
	document.getElementsByTagName("head")[0].appendChild(link)

	const labelStyleColorExpression = [
		'case',
		['boolean', ['feature-state', 'active'], false],
		"#f5a300",
		"#111111"
	]

	const CABLE_SECTION = 'cableSection'
	const EQUIPMENTS = ['branchBox', 'tower', 'ringBox', 'electricityRoom', 'compactSubstation', 'turnPoint',
		"switchStation"
	]
	const CHANNELS = ['dingguan', 'guangou', 'otherData', 'paiguan', 'qiaojia', 'zhimai', 'suidao', 'xuniguangou']

	let selectedFeature = null // {id:xxx,source:xxx}

	// 定位线路后，线路和设备需要一直保持高亮
	let highlightSubstationLine = {
		id: '',
		equipments: {}
	}

	export default {
		data() {
			return {
				map: null,
				gdMap: null,
				allLayers: []
			}
		},
		computed: {
			...mapState
		},
		mounted() {
			// 在组件挂载后添加点击事件监听器
			const tabHeaders = document.querySelectorAll('.tab-header-item');
			const tabPanes = document.querySelectorAll('.tab-pane');
			tabHeaders.forEach((header, index) => {
				header.addEventListener('click', () => {
					// 清除所有标签的 active 状态
					tabHeaders.forEach(h => h.classList.remove('active'));
					tabPanes.forEach(p => p.classList.remove('active'));

					// 设置当前点击的标签为 active
					header.classList.add('active');
					tabPanes[index].classList.add('active');
				});
			});

			this.loadLibs()
			if (!isOpenDatabase()) {
				openDatabase().then(() => {
					this.initPos()
				}).catch(e => {
					console.error("打开DB失败：", e)
				})
			} else {
				this.initPos()
			}
			// 触发电缆井详情
			propertiesPanel = document.getElementById("properties-panel")
			window.zoomMapTo = function zoomMapTo(lngLat, level) {
				window.map.flyTo({
					center: lngLat,
					zoom: level,
					speed: 2
				})
			}
			window.navigateToWellProfile = this.navigateToWellProfile
		},
		methods: {
			
			emitData(e, ownerVm) {
				console.log(e, ownerVm);
			},

			loadLibs() {
				const script = document.createElement('script')
				// 引入lodash
				script.src = 'static/lib/lodash.js'
				document.head.appendChild(script)
			},

			//初始化地图
			loadFile(filename) {
				if (!filename) {
					throw "filename is required"
				}
				return loadStaticData(filename)
			},
			generatePropertiesTable(title, properties) {
				const keys = Object.keys(properties)

				let str = ''
				for (let i = 0; i < keys.length; i += 2) {
					const leftKey = keys[i]
					const rightKey = keys[i + 1]
					str += '<tr>'
					if (typeof properties[leftKey] === 'string' || typeof properties[leftKey] === 'number') {
						str += `<td width='50%'>${leftKey}：${properties[leftKey]}</td>`
					}
					if (rightKey && (typeof properties[rightKey] === 'string' || typeof properties[rightKey] ===
							'number')) {
						str += `<td width='50%'>${rightKey}：${properties[rightKey]}</td>`
					}
					str += '</tr>'
				}
				return `
		<table class="properties-table" width="100%" cellspacing="0" cellpadding="10">
			${str}
		</table>
	`
			},
			showPanel() {
				propertiesPanel.style.zIndex = 99
			},
			hidePanel() {
				propertiesPanel.style.zIndex = -1
			},
			setPanelContent(title, properties, pos, lineName, type) {
				const coordinates = _.get(pos, ["geometry", "coordinates"])
				const des = _.get(pos, ["properties", "name"]) // 导航目的地描述
				if (!properties && !title) {
					return
				}
				let position;
				if (EQUIPMENTS.indexOf(type) > -1 || type === 'cableWell' || type === 'substation') {
					position = '导航'
				} else {
					position = ''
				}
				propertiesPanel.querySelector(".title").textContent = title
				propertiesPanel.querySelector("#address").textContent = position
				propertiesPanel.querySelector(".table-container").innerHTML = this.generatePropertiesTable(title,
					properties, type)
				navigationData = {
					coordinates,
					des,
					type
				}
			},
			loadEquipmetLayer(name, iconName) {
				const dataSourceName = `equipment-${name}`
				const layerName = `equipment-${name}-layer`
				const highlightlayerName = `equipment-${name}-layer-highlighted`

				return loadBitmap(iconName).then(image => {
					const imageId = `icon-${name}`
					const highlightedImageId = `icon-${name}-highlighted`

					this.map.addImage(imageId, image);
					replaceImageColor("#f5a300", image).then(img => {
						map.addImage(highlightedImageId, img)
					}).then(() => {
						return this.loadFile(`${dataSourceName}.geojson`).then(geo => {
							map.addSource(dataSourceName, {
								type: "geojson",
								data: geo,
								promoteId: "id",
							});
							map.addLayer({
								id: layerName,
								type: "symbol",
								minzoom: 12,
								source: dataSourceName, // reference the data source
								'layout': {
									'icon-image': imageId, // reference the image
									'icon-size': 0.5,
									'text-field': ['get', 'name'],
									"text-anchor": "top-left",
									"text-size": 12,
									"text-offset": [0.5, 0.2],
								},
								paint: {
									"text-color": "#111111"
								}
							});
							map.addLayer({
								id: highlightlayerName,
								'type': 'symbol',
								minzoom: 12,
								source: dataSourceName, // reference the data source
								'layout': {
									'icon-image': highlightedImageId, // reference the image
									'icon-size': 0.5,
									'text-field': ['get', 'name'],
									"text-anchor": "top-left",
									"text-size": 12,
									"text-offset": [0.6, 0.2],
								},
								paint: {
									"text-color": "#f5a300"
								},
								filter: ["in", "id", ''],
							});
						})
					})
				})
			},
			loadChannelTowerLayer() {
				const name = 'tower'
				const dataSourceName = `equipment-${name}`
				const layerName = `equipment-${name}-layer`
				const highlightlayerName = `equipment-${name}-layer-highlighted`

				return Promise.all([
					loadBitmap('cementtower.png'), //水泥杆
					loadBitmap('steeltower.png'), //钢管杆
					loadBitmap('tower.png'), // jiaogangTower, gangguanTower
					loadBitmap('unknowtower.png'), // 未定杆塔，其他杆
					loadBitmap('woodtower.png'), // 木杆
				]).then(res => {
					const [icon1, icon2, icon3, icon4, icon5] = res

					return Promise.all([
						replaceImageColor("#f5a300", icon1),
						replaceImageColor("#f5a300", icon2),
						replaceImageColor("#f5a300", icon3),
						replaceImageColor("#f5a300", icon4),
						replaceImageColor("#f5a300", icon5),
					]).then(res => {
						const [icon1WithYellow, icon2WithYellow, icon3WithYellow, icon4WithYellow,
							icon5WithYellow
						] = res

						this.map.addImage('tower_icon1', icon1)
						this.map.addImage('tower_icon2', icon2)
						this.map.addImage('tower_icon3', icon3)
						this.map.addImage('tower_icon4', icon4)
						this.map.addImage('tower_icon5', icon5)
						this.map.addImage('tower_icon1_with_yellow', icon1WithYellow)
						this.map.addImage('tower_icon2_with_yellow', icon2WithYellow)
						this.map.addImage('tower_icon3_with_yellow', icon3WithYellow)
						this.map.addImage('tower_icon4_with_yellow', icon4WithYellow)
						this.map.addImage('tower_icon5_with_yellow', icon5WithYellow)

						const useIcon1 = ['==', ['get', 'type'], 'ShuiNiGan']
						const useIcon2 = ['==', ['get', 'type'], 'GangGuanGan']
						const useIcon3 = ['==', ['get', 'type'], 'JiaoGangTower']
						const useIcon4 = ['==', ['get', 'type'], 'Undefine']
						const useIcon5 = ['==', ['get', 'type'], 'MuGan']
						const useIcon6 = ['==', ['get', 'type'], 'GangGuanTower'] // 和JiaoGangTower使用相同图标
						const useIcon7 = ['==', ['get', 'type'], 'OtherTowerType'] // 和Undefine使用相同图标

						return this.loadFile(`${dataSourceName}.geojson`).then(geo => {
							map.addSource(dataSourceName, {
								type: "geojson",
								data: geo,
								promoteId: "id",
							});
							map.addLayer({
								id: layerName,
								type: "symbol",
								minzoom: 12,
								source: dataSourceName, // reference the data source
								'layout': {
									'icon-image': [
										'case',
										useIcon1,
										'tower_icon1',
										useIcon2,
										'tower_icon2',
										useIcon3,
										'tower_icon3',
										useIcon4,
										'tower_icon4',
										useIcon5,
										'tower_icon5',
										useIcon6,
										'tower_icon3',
										useIcon7,
										'tower_icon4',
										'tower_icon1',
									], // reference the image
									'icon-size': 0.5,
									'text-field': ['get', 'name'],
									"text-anchor": "top-left",
									"text-size": 12,
									"text-offset": [0.5, 0.2],
								},
								paint: {
									"text-color": "#111111"
								}
							});
							map.addLayer({
								id: highlightlayerName,
								'type': 'symbol',
								minzoom: 12,
								source: dataSourceName, // reference the data source
								'layout': {
									'icon-image': [
										'case',
										useIcon1,
										'tower_icon1_with_yellow',
										useIcon2,
										'tower_icon2_with_yellow',
										useIcon3,
										'tower_icon3_with_yellow',
										useIcon4,
										'tower_icon4_with_yellow',
										useIcon5,
										'tower_icon5_with_yellow',
										useIcon6,
										'tower_icon3_with_yellow',
										useIcon7,
										'tower_icon4_with_yellow',
										'tower_icon1_with_yellow',
									],
									'icon-size': 0.5,
									'text-field': ['get', 'name'],
									"text-anchor": "top-left",
									"text-size": 12,
									"text-offset": [0.6, 0.2],
								},
								paint: {
									"text-color": "#f5a300"
								},
								filter: ["in", "id", ''],
							});
						})
					})
				})
			},
			locateRoute(treeNode, oldValue, ownerinstance) {
				this.ownerinstance = ownerinstance
				if (!this.map) {
					// 地图初始化之前会执行一次
					return
				}
				this.clearHighlight() //把之前的高亮清除掉
				const {
					id,
					type,
					eqType
				} = treeNode
				if (type === 'cableSection') {
					// 定位到电缆段
					this.locateCableSection(id)
				} else if (type === "substationLine" || type === 'line') {
					// 定位线路, 线路定位后需要一直保持高亮，直到点特定按钮之后才取消高亮
					this.locateSubstationLine(treeNode)
				} else if (eqType || EQUIPMENTS.indexOf(type) > -1) {
					this.locateEquipments(id)
				} else if (type === 'cableWell') {
					this.locateCableWell(id)
				} else if (type === 'substation') {
					// 定位变电站，单点定位，非整个路线定位
					this.locateSubstation(id)
				} else if (CHANNELS.indexOf(type) > -1) {
					// 定位通道
					this.locateChannel(id)
				} else if (type === 'cableConnector') {
					// 接头
					this.locateCableConnector(id)
				}
				

				if (CHANNELS.indexOf(type) > -1) {
					this.showSelectedFeatureProperties(id, "channel-")
				} else if (type === 'cableWell') {
					this.showCableWellProperties(id)
				} else {
					this.showSelectedFeatureProperties(id)
				}
			},
			locateCableSection(id) {
				selectSql(`select * from tzinfo where id='${id}'`).then((result) => {
					console.log("cableSection 定位 id：", id)
					const targetGeometryJSON = _.get(result, [0, "pos"])
					if (!targetGeometryJSON) {
						return
					}
					if (!this.map.getLayer('cableSection-layer-highlighted')) {
						this.toastLayerLoading();
						return
					}
					const targetGeometry = JSON.parse(targetGeometryJSON)

					const coordinates = targetGeometry.geometry.coordinates
					const bounds = new mapboxgl.LngLatBounds(
						coordinates[0][0],
						coordinates[0][1]
					)
					for (const coord of coordinates) {
						bounds.extend(coord[0])
						bounds.extend(coord[1])
					}

					this.map.fitBounds(bounds, {
						padding: 20,
					})


					// 需要判断下图层是否存在
					if (this.map.getLayer('cableSection-layer-highlighted')) {
						this.map.setFilter('cableSection-layer-highlighted', ['in', 'id', id]);
					}
				})
			},
			locateSubstationLine(treeNode) {
				// 库里的数据用来定位，高亮使用filter高亮或者feature-state
				// 搜索拿到的数据和左侧点的数据不同
				const {
					id
				} = treeNode
				selectSql(`select * from tzinfo where id='${id}'`).then((result) => {
					highlightSubstationLine.id = id
					// 查询线路下所有geometry
					const substationLineGeoJSON = _.get(result, [0, "pos"])
					const substationLineGeoObject = JSON.parse(substationLineGeoJSON)
					const features = substationLineGeoObject.features

					const bounds = new mapboxgl.LngLatBounds()

					for (const feature of features) {
						const geometry = feature.geometry

						const type = geometry.type
						if (type === 'Point') {
							const coord = geometry.coordinates
							bounds.extend(coord)
						} else if (type === 'MultiLineString') {
							const coordinates = geometry.coordinates
							for (const coord of coordinates) {
								bounds.extend(coord[0])
								bounds.extend(coord[1])
							}
						}
					}
					this.map.fitBounds(bounds, {
						padding: 20,
					})
				}).then(() => {
					selectSql(`select * from tzinfo where lineId like '%${id}%'`).then(res => {
						const cableSectionsShouldHighlight = res.filter(i => i.type === 'cableSection')
							.map(i => i.id)
						const equipments = res.filter(i => i.type !== 'cableSection')
						// 高亮显示
						this.map.setFilter('cableSection-layer-highlighted', ['in', 'id', ...
							cableSectionsShouldHighlight
						]);
						const grouped = _.groupBy(equipments, 'type')

						_.forEach(grouped, (value, key) => {
							const highlightIds = value.map(i => i.id)
							highlightSubstationLine.equipments[key] = highlightIds
							// 高亮显示设备图层
							this.map.setFilter(`equipment-${key}-layer-highlighted`, ['in', 'id',
								...highlightIds
							]);
						})

						document.getElementById('button-cancel-highlight-route').style.zIndex = 103
					})
				}).catch(e => {
					console.error(e)
				})
			},
			locateEquipments(id) {
				selectSql(`select * from tzinfo where id='${id}'`).then(res => {
					const equipment = res[0]
					const {
						type,
						pos
					} = equipment
					const parsedPos = JSON.parse(pos)
					console.log("equipment 位置信息：", parsedPos);
					const coordinates = _.get(parsedPos, ["geometry", "coordinates"])
					this.map.flyTo({
						center: coordinates,
						zoom: 20
					})
					this.map.setFilter(`equipment-${type}-layer-highlighted`, ['in', 'id', id]);
				})
			},
			//定位到电缆井并且高亮显示
			locateCableWell(id) {
				selectSql(`select * from tzinfo where id='${id}'`).then(res => {
					const cableWell = res[0]
					const {
						type,
						pos
					} = cableWell
					const parsedPos = JSON.parse(pos)
					console.log("cableWell 位置信息：", parsedPos);
					const coordinates = _.get(parsedPos, ["geometry", "coordinates"])
					this.map.flyTo({
						center: coordinates,
						zoom: 20
					})
					this.map.setFilter(`cableWell-layer-highlighted`, ['in', 'id', id]);
					selectedFeature = {
						source: 'cableWell',
						id: id
					}
					this.map.setFeatureState(selectedFeature, {
						active: true
					});
				})
			},
			locateCableConnector(id) {
				selectSql(`select * from tzinfo where id='${id}'`).then(res => {
					const cableConnector = res[0]
					const {
						type,
						pos
					} = cableConnector
					const parsedPos = JSON.parse(pos)
					console.log("cableConnector 位置信息：", parsedPos);
					const coordinates = _.get(parsedPos, ["geometry", "coordinates"])
					this.map.flyTo({
						center: coordinates,
						zoom: 20
					})
				})
			},
			locateSubstation(id) {
				selectSql(`select * from tzinfo where id='${id}'`).then(res => {
					const substation = res[0]
					const {
						type,
						pos
					} = substation
					const parsedPos = JSON.parse(pos)
					const coordinates = _.get(parsedPos, ["geometry", "coordinates"])
					this.map.flyTo({
						center: coordinates,
						zoom: 20
					})
					this.map.setFilter(`substation-layer-highlighted`, ['in', 'id', id]);
					selectedFeature = {
						source: 'substation',
						id: id
					}
					this.map.setFeatureState(selectedFeature, {
						active: true
					});
				})
			},
			locateChannel(id) {
				console.log('channel id:', id)
				selectSql(`select * from tzinfo where id='${id}'`).then(res => {
					const channel = res[0]
					const {
						type,
						pos
					} = channel
					const parsedPos = JSON.parse(pos)
					console.log("channel 位置信息：", parsedPos);
					const coordinates = _.get(parsedPos, ["geometry", "coordinates"])
					if (coordinates) {
						const bounds = new mapboxgl.LngLatBounds(coordinates)

						this.map.fitBounds(bounds, {
							padding: 20,
						})
					}

					const highlightedLayerName = `channel-${type}-layer-highlighted`
					const highlightedLabelLayerName = `channel-${type}-label-layer-highlighted`
					this.map.setFilter(highlightedLayerName, ['in', 'id', id]);

					selectedFeature = {
						source: `channel-${type}`,
						id: id
					}
					this.map.setFeatureState(selectedFeature, {
						active: true
					});
				})
			},
			loadChannelLayer(name, iconName) {
				const datasourceName = `channel-${name}`
				const layerName = `channel-${name}-layer`
				const highlightedLayerName = `channel-${name}-layer-highlighted`
				const labelLayerName = `channel-${name}-label-layer`
				const highlightedLabelLayerName = `channel-${name}-label-layer-highlighted`

				return loadBitmap(iconName).then(image => {
					const imageId = `icon-${name}`
					this.map.addImage(imageId, image);

					return this.loadFile(`${datasourceName}.geojson`).then(geo => {
						this.map.addSource(datasourceName, {
							type: "geojson",
							data: geo,
							promoteId: "id",
						});
						this.map.addLayer({
							id: layerName,
							type: "line",
							source: datasourceName,
							paint: {
								"line-pattern": imageId,
								"line-width": 10,
							},
						});
						//高亮图层放下面
						this.map.addLayer({
							id: highlightedLayerName,
							'type': 'line',
							source: datasourceName,
							paint: {
								"line-width": 10,
								"line-color": "#f5a300",
								"line-opacity": 0.5
							},
							filter: ["in", "id", ""]
						});

						// 加载lable高亮图层
						this.map.addLayer({
							id: highlightedLabelLayerName,
							type: "symbol",
							source: datasourceName,
							// minzoom:16,
							layout: {
								"symbol-placement": "line-center",
								"text-offset": [0, -1],
								'text-field': ['get', 'name'],
								"text-size": 12,
							},
							paint: {
								"text-color": labelStyleColorExpression
							},
						});
					})
				})
			},
			loadCableConnector() {
				const name = "cableConnector"
				const map = this.map
				return this.loadFile('cableConnector.geojson').then(geo => {
					map.addSource("cableConnector", {
						type: "geojson",
						data: geo,
						promoteId: "id",
					});
					loadBitmap("cableConnector.png").then(image => {
						map.addImage('cableConnectorIcon', image);
						replaceImageColor("#f5a300", image).then(img => {
							map.addImage('cableConnectorIconHighlighted', img)
							map.addLayer({
								id: "cableConnector-layer",
								'type': 'symbol',
								minzoom: 16,
								source: "cableConnector",
								'layout': {
									'icon-image': "cableConnectorIcon",
									'icon-size': 0.5,
								},
								paint: {
									"text-color": "#111111"
								}
							});
							map.addLayer({
								id: "cableConnector-layer-highlighted",
								'type': 'symbol',
								minzoom: 16,
								source: "cableConnector", // reference the data source
								'layout': {
									'icon-image': 'cableConnectorIconHighlighted', // reference the image
									'icon-size': 0.5,
								},
								filter: ["in", "id", ""],
								paint: {
									"text-color": labelStyleColorExpression
								}
							});
						})
					})
				})
			},
			findCableSectionById(features, id) {
				const len = features.length
				for (let i = 0; i < len; i++) {
					const feature = features[i]

					if (feature.id === id) {
						return feature
					}
				}
				return null
			},
			clearHighlight() {
				this.hidePanel()
				const p = /\w*-highlighted$/g
				const highlightedLayers = this.map.getStyle().layers.filter(i => p.test(i.id))
				console.log('cleared highlighted:', highlightedLayers)
				console.log('highlightSubstationLine', highlightSubstationLine)
				const highlightEqsLayersByLocateSubstationLine = Object.keys(highlightSubstationLine.equipments).map(i =>
					`equipment-${i}-layer-highlighted`)
				highlightedLayers.forEach(layer => {
					if (highlightEqsLayersByLocateSubstationLine.indexOf(layer.id) > -1) {
						const type = layer.id.split('-')[1]
						// 把已经高亮的重新渲染一遍
						this.map.setFilter(layer.id, [
							'in',
							"id",
							...highlightSubstationLine.equipments[type]
						]);
						return
					}
					if (highlightSubstationLine.id && layer.id === "cableSection-layer-highlighted") {
						return
					}
					this.map.setFilter(layer.id, [
						'in',
						"id",
						""
					]);
				})
				if (selectedFeature) {
					this.map.setFeatureState(selectedFeature, {
						active: false
					});
					selectedFeature = null
				}

				// 通道和电缆段属性面板关闭
				document.getElementById('channel-panel').classList.remove('show')
				document.getElementById('channel-tab-channel').classList.add('active')
				document.getElementById('channel-tab-cable').classList.remove('active')
				document.getElementById('tab1').classList.add('active')
				document.getElementById('tab2').classList.remove('active')

				// 电缆井属性面板关闭  点击电缆井图标触发
				document.getElementById('cable-well-panel').style.zIndex = -1

				// 接头数据面板关闭
				const connectorListContainer = document.getElementById('connector-list')
				const connectorDetailPane = document.getElementById('connector-detail-pane')
				const connectorDetail = document.getElementById('connector-detail')

				connectorDetailPane.scrollTop = 0
				connectorDetailPane.classList.remove('active')
			},
			navigateToWellProfile(id) {
				uni.navigateTo({
					url: '/pages/well/index?id=' + id
				})
			},
			showSelectedFeatureProperties(selectedStateId, layerName) {
				selectSql(
					`select * from tzinfo where id='${selectedStateId}'`).then(result => {
					const res = result[0]
					const name = res.typeCN
					const type = res.type

					try {
						const pos = JSON.parse(res.pos)
						const detail = JSON.parse(res.detail)

						if (layerName && _.startsWith(layerName, "channel-")) {
							// 管道
							const cableSections = detail['电缆段列表']
							const html = cableSections.map(i =>
								`<uni-view class="cable-list-item" id="${i["电缆段ID"]}">${i["电缆段名称"]}</uni-view>`
							).join('')
							const tab1El = document.getElementById('tab1')
							const tab2El = document.getElementById('tab2')

							tab2El.innerHTML = html
							//控制通道弹窗
							document.getElementById('channel-panel').classList.add('show')
							const tab1Content = this.generatePropertiesTable(name, detail)
							tab1El.innerHTML = tab1Content

							const channelTab_channel = document.getElementById('channel-tab-channel')
							const channelTab_cable = document.getElementById('channel-tab-cable')

							channelTab_channel.onclick = (e) => {
								tab1El.classList.add('active')
								tab2El.classList.remove('active')
								channelTab_channel.classList.add('active')
								channelTab_cable.classList.remove('active')
							}
							channelTab_cable.onclick = () => {
								tab2El.classList.add('active')
								tab1El.classList.remove('active')
								channelTab_channel.classList.remove('active')
								channelTab_cable.classList.add('active')
							}

							return
						}

						this.setPanelContent(name, detail, pos, '', type)
						this.showPanel()
					} catch (e) {
						console.error(e)
					}
				})
			},
			showCableWellProperties(id) {
				selectSql(
					`select * from tzinfo where id='${id}'`).then(result => {
					const res = result[0]
					const name = res.typeCN
					const type = res.type

					try {
						const pos = JSON.parse(res.pos)
						const detail = JSON.parse(res.detail)
						const cableConnectors = detail['接头']
						const properties = detail
						const keys = Object.keys(properties)
						let str = ''
						for (let i = 0; i < keys.length; i += 2) {
							const leftKey = keys[i]
							const rightKey = keys[i + 1]
							str += '<tr>'
							if (typeof properties[leftKey] === 'string' || typeof properties[leftKey] ===
								'number') {
								str += `<td width='50%'>${leftKey}：${properties[leftKey]}</td>`
							}
							if (rightKey && (typeof properties[rightKey] === 'string' || typeof properties[
										rightKey] ===
									'number')) {
								str += `<td width='50%'>${rightKey}：${properties[rightKey]}</td>`
							}
							str += '</tr>'
						}
						str = `
						<table class="properties-table" width="100%" cellspacing="0" cellpadding="10">
							${str}
						</table>
					`
						if (cableConnectors && cableConnectors.length > 0) {
							console.log('cableConnectors:', cableConnectors)
							const cableConnectorIds = cableConnectors.map(c => `'${c.id}'`).join(',')
							console.log('cableConnectorIds:', cableConnectorIds)
							selectSql(`select * from tzinfo where id in (${cableConnectorIds})`).then(res => {
								console.log('查询到的接头：', res)
								const panel = document.getElementById('cable-well-panel')
								const tab3 = panel.querySelector('#tab3')
								const tab4 = panel.querySelector('#tab4')
								const tabBtn3 = panel.querySelector('#cable-well-tab-1')
								const tabBtn4 = panel.querySelector('#cable-well-tab-2')
								tab3.classList.add('active')
								tab4.classList.remove('active')
								tabBtn3.classList.add('active')
								tabBtn4.classList.remove('active')

								tabBtn3.onclick = (e) => {
									tab3.classList.add('active')
									tab4.classList.remove('active')
									tabBtn3.classList.add('active')
									tabBtn4.classList.remove('active')
								}
								tabBtn4.onclick = () => {
									tab4.classList.add('active')
									tab3.classList.remove('active')
									tabBtn4.classList.add('active')
									tabBtn3.classList.remove('active')
								}

								tab3.innerHTML = str
								// 列出所有的接头
								const connectorListContainer = document.getElementById('connector-list')
								const connectorDetailPane = document.getElementById(
									'connector-detail-pane')
								const connectorDetail = document.getElementById('connector-detail')
								const btnBackToList = document.getElementById('back-to-list')
								connectorListContainer.innerHTML = res.map((c, index) => {
									const properties = JSON.parse(c.detail)
									const keys = Object.keys(properties)
									return `<div class="connector-list-container">
										<div id='connector-${index}'>${properties['名称']}</div>
									</div>`
								}).join('')
								connectorListContainer.onclick = e => {
									if (e.target.id) {
										let index = e.target.id.split('-')[1]

										if (index !== undefined) {

											index = parseInt(index)

											let str = ''
											const properties = res[index] && JSON.parse(res[index]
												.detail)
											const keys = Object.keys(properties)
											console.log('点击列表：', properties)

											for (let i = 0; i < keys.length; i += 2) {
												const leftKey = keys[i]
												const rightKey = keys[i + 1]
												str += '<tr>'
												if (typeof properties[leftKey] === 'string' ||
													typeof properties[leftKey] === 'number') {
													str +=
														`<td width='50%'>${leftKey}：${properties[leftKey]}</td>`
												}
												if (rightKey && (typeof properties[rightKey] ===
														'string' || typeof properties[rightKey] ===
														'number')) {
													str +=
														`<td width='50%'>${rightKey}：${properties[rightKey]}</td>`
												}
												str += '</tr>'
											}
											str = `
											<table class="properties-table" width="100%" cellspacing="0" cellpadding="10">
												${str}
											</table>
										`
											connectorDetail.innerHTML = str
											connectorDetailPane.classList.add('active')
										}
									}

								}

								btnBackToList.onclick = e => connectorDetailPane.classList.remove('active')

								panel.style.zIndex = 100
							})
							const coordinates = _.get(pos, ["geometry", "coordinates"])
							const des = _.get(pos, ["properties", "name"]) // 导航目的地描述
							navigationData = {
								coordinates,
								des,
								type
							}
						} else {
							this.setPanelContent(name, detail, pos, '', type)
							this.showPanel()
						}
					} catch (e) {
						console.error(e)
					}
				})
			},
			navigateToWellProfile(id) {
				uni.navigateTo({
					url: '/pages/well/index?id=' + id
				})
			},
			showToast(message, duration = 2000) {
				const toast = document.getElementById('toast')
				toast.textContent = message
				toast.style.zIndex = 100
				setTimeout(() => {
					toast.style.zIndex = -1
				}, duration);
			},
			hideToast() {
				const toast = document.getElementById('toast')
				toast.style.zIndex = -1
			},
			async initPos() {
				var center = []
				await loadStaticData('substation.geojson')
					.then(result => {
						center = result.features[0].geometry.coordinates
						this.initMap(center)
					})
					.catch(e => {
						console.error(e);
					});
			},
			initMap(center) {
				mapboxgl.accessToken =
					"pk.eyJ1IjoiZm91cmtpbG9taXRlcnMiLCJhIjoiY2lxZzBzcWJnMDN1ZGZ3bTFzMmdta3l4ZSJ9.AXqPxz4eauI7eOYfaL4eyA";

				var tileset = "mapbox.fourkilomiters.90yq9gbt";

				const map = new mapboxgl.Map({
					container: "map-box", // container ID
					// center: [120.200764509977, 33.3651903562515], // starting position [lng, lat]
					center: center, // starting position [lng, lat]
					zoom: 11, // starting zoom
					projection: "globe", // display the map as a 3D globe
					style: vecBaseMapStyle,
					localIdeographFontFamily: null
				});
				
				// 实例化GeolocateControl
				var geolocate = new mapboxgl.GeolocateControl({
				  positionOptions: {
				    enableHighAccuracy: true // 是否启用高精度模式
				  },
				  trackUserLocation: true // 是否跟踪用户位置
				});
				 
				// 添加GeolocateControl到地图
				map.addControl(geolocate);
				
				window.map = map
				this.map = map
				map.addControl(new mapboxgl.NavigationControl());
				map.addControl(legendControl);
				map.addControl(basemapSwitchControl)

				map.on("load", () => {
					Promise.all([
						this.loadChannelLayer("dingguan", "dingguan.png"),
						this.loadChannelLayer("guangou", "guangou.png"),
						this.loadChannelLayer("otherData", "qitamaishe.png"),
						this.loadChannelLayer("paiguan", "paiguan.png"),
						this.loadChannelLayer("qiaojia", "qiaojia.png"),
						this.loadChannelLayer("zhimai", "zhimai.png"),
						this.loadChannelLayer("xuniguangou", "xuniguangou.png"),
						this.loadChannelLayer("suidao", "suidao.png")
					]).then(() => {
						//电缆井
						return this.loadFile('cableWell.geojson').then(geo => {
							map.addSource("cableWell", {
								type: "geojson",
								data: geo,
								promoteId: "id",
							});
							return Promise.all([
								loadBitmap("regcablewell.png"),
								loadBitmap("cableWell1.png"),
								loadBitmap("unknowcablewell2.png")
							]).then((res) => {
								/**
								 * regcablewell 方形井盖
								 * cableWell1   圆形井盖
								 * unknowcablewell2 其他 和 未定义
								 */
								const [image1, image2, image3] = res

								return Promise.all([overlapConnectorIcon(image1),
									overlapConnectorIcon(image2),
									overlapConnectorIcon(image3)
								]).then(res => {
									const [overlapIcon1, overlapIcon2,
										overlapIcon3
									] = res

									return Promise.all([
										replaceImageColor("#f5a300",
											image1),
										replaceImageColor("#f5a300",
											image2),
										replaceImageColor("#f5a300",
											image3),
										replaceImageColor("#f5a300",
											overlapIcon1),
										replaceImageColor("#f5a300",
											overlapIcon2),
										replaceImageColor("#f5a300",
											overlapIcon2)
									], ).then(res => {
										const [image1WithYellow,
											image2WithYellow,
											image3WithYellow,
											overlapIcon1WithYellow,
											overlapIcon2WithYellow,
											overlapIcon3WithYellow
										] = res

										map.addImage('image1', image1);
										map.addImage('image2', image2);
										map.addImage('image3', image3);
										map.addImage('overlapIcon1',
											overlapIcon1);
										map.addImage('overlapIcon2',
											overlapIcon2);
										map.addImage('overlapIcon3',
											overlapIcon3);
										map.addImage('image1WithYellow',
											image1WithYellow);
										map.addImage('image2WithYellow',
											image2WithYellow);
										map.addImage('image3WithYellow',
											image3WithYellow);
										map.addImage(
											'overlapIcon1WithYellow',
											overlapIcon1WithYellow);
										map.addImage(
											'overlapIcon2WithYellow',
											overlapIcon2WithYellow);
										map.addImage(
											'overlapIcon3WithYellow',
											overlapIcon3WithYellow);

										// 没有接头的各种类型的井
										const useImage1 = ['all', ['==', [
												'get',
												'connector_count'
											], 0],
											['==', ['get', 'type'],
												'方形'
											]
										]
										const useImage2 = ['all', ['==', [
												'get',
												'connector_count'
											], 0],
											['==', ['get', 'type'],
												'圆形'
											]
										]
										const useImage3 = ['all', ['==', [
												'get',
												'connector_count'
											], 0],
											['==', ['get', 'type'],
												'其他'
											]
										]
										const useImage4 = ['all', ['==', [
												'get',
												'connector_count'
											], 0],
											['==', ['get', 'type'],
												'未定义'
											]
										]

										// 带有接头的各种类型的井
										const useOverlapIcon1 = ['all', [
												'>', ['get',
													'connector_count'
												], 0
											],
											['==', ['get', 'type'],
												'方形'
											]
										]
										const useOverlapIcon2 = ['all', [
												'>', ['get',
													'connector_count'
												], 0
											],
											['==', ['get', 'type'],
												'圆形'
											]
										]
										const useOverlapIcon3 = ['all', [
												'>', ['get',
													'connector_count'
												], 0
											],
											['==', ['get', 'type'],
												'其他'
											]
										]
										const useOverlapIcon4 = ['all', [
												'>', ['get',
													'connector_count'
												], 0
											],
											['==', ['get', 'type'],
												'未定义'
											]
										]
										map.addLayer({
											id: "cableWell-layer",
											'type': 'symbol',
											minzoom: 16,
											source: "cableWell",
											'layout': {
												'icon-image': [
													'case',
													useImage1,
													'image1',
													useImage2,
													'image2',
													useImage3,
													'image3',
													useImage4,
													'image3',
													useOverlapIcon1,
													'overlapIcon1',
													useOverlapIcon2,
													'overlapIcon2',
													useOverlapIcon3,
													'overlapIcon3',
													useOverlapIcon4,
													'overlapIcon3',
													'image1',
												],
												'icon-size': 0.5,
												'text-field': [
													'get',
													'name'
												],
												"text-anchor": "top-left",
												"text-size": 12,
												"text-offset": [
													0.5, 0.2
												],
											},
											paint: {
												"text-color": "#111111"
											}
										});
										map.addLayer({
											id: "cableWell-layer-highlighted",
											'type': 'symbol',
											minzoom: 16,
											source: "cableWell", // reference the data source
											'layout': {
												'icon-image': [
													'case',
													useImage1,
													'image1WithYellow',
													useImage2,
													'image2WithYellow',
													useImage3,
													'image3WithYellow',
													useImage4,
													'image3WithYellow',
													useOverlapIcon1,
													'overlapIcon1WithYellow',
													useOverlapIcon2,
													'overlapIcon2WithYellow',
													useOverlapIcon3,
													'overlapIcon3WithYellow',
													useOverlapIcon4,
													'overlapIcon3WithYellow',
													'image1WithYellow'
												],
												'icon-size': 0.5,
												'text-field': [
													'get',
													'name'
												],
												"text-anchor": "top-left",
												"text-size": 12,
												"text-offset": [
													0.5, 0.2
												],
											},
											filter: ["in", "id",
												""
											],
											paint: {
												"text-color": labelStyleColorExpression
											}
										});
									})
								})
							})

						})
					}).then(() => {
						console.log('加载Equipment')
						// 加载Equipment各个图层
						return Promise.all([
							this.loadEquipmetLayer("branchBox", "branchBox.png"),
							this.loadChannelTowerLayer(),
							this.loadEquipmetLayer("turnPoint", "gdmap.png"),
							this.loadEquipmetLayer("ringBox", "ringBox.png"),
							this.loadEquipmetLayer("switchStation", "switchStation.png"),
							this.loadEquipmetLayer("electricityRoom", "electricityRoom.png"),
							this.loadEquipmetLayer("compactSubstation", "compactSubstation.png")
						])
					}).then(() => {
						//变电站
						return this.loadFile('substation.geojson').then(geo => {
							loadBitmap("bdzmap.png").then(image => {
								map.addImage('substationIcon', image);
								map.addSource("substation", {
									type: "geojson",
									data: geo,
									promoteId: "id",
								});

								map.addLayer({
									id: "substation-layer",
									type: "symbol",
									source: "substation", // reference the data source
									'layout': {
										'icon-image': 'substationIcon', // reference the image
										'icon-size': 0.75,
										'text-field': ['get', 'name'],
										"text-anchor": "top-left",
										"text-size": 12,
										"text-offset": [0.5, 0.2],
									},
									paint: {
										"text-color": "#111111"
									}
								});

								return replaceImageColor("#f5a300", image).then(img => {
									map.addImage('substationHighLightIcon', img);
									map.addLayer({
										id: "substation-layer-highlighted",
										type: "symbol",
										source: "substation", // reference the data source
										'layout': {
											'icon-image': 'substationHighLightIcon', // reference the image
											'icon-size': 0.75,
											'text-field': ['get', 'name'],
											"text-anchor": "top-left",
											"text-size": 12,
											"text-offset": [0.6, 0.2],
										},
										paint: {
											"text-color": labelStyleColorExpression
										},
										filter: ["in", "id", ''],
									});
								}).catch(e => {
									console.error('加载substation高亮图层失败')
								})
							})
						})
					}).then(() => {
						// 加载cableSection（电缆段）文件
						return this.loadFile('cableSection.geojson').then(geo => {
							map.addSource("cableSection", {
								type: "geojson",
								data: geo,
								promoteId: 'id'
							});
							map.addLayer({
								id: "cableSection-layer",
								type: "line",
								source: "cableSection", // reference the data source
								'paint': {
									'line-color': "#fd0100",
									'line-width': 2,
									"line-dasharray": [2, 4]
								}
							}, "cableWell-layer");
							map.addLayer({
								id: "cableSection-layer-highlighted",
								type: "line",
								source: "cableSection", // reference the data source
								'paint': {
									'line-color': 'rgba(0,0,254,1)',
									'line-width': 3,
									// "line-dasharray": [2, 4],
								},
								filter: ["in", "id", ""]
							}, "cableWell-layer");
						})
					}).catch(e => {
						console.error(e)
					}).then(() => {
						map.on('click', "cableWell-layer", (e) => {
							const coordinates = e.features[0].geometry.coordinates.slice();
							const name = e.features[0].properties.name;
							const id = e.features[0].id

							new mapboxgl.Popup()
								.setLngLat(coordinates)
								.setHTML(
									`<div><p>${name}</p><span class="deepTo" onclick="window.navigateToWellProfile('${id}')">查看剖面</span></div>`
								)
								.addTo(map);
							this.showCableWellProperties(id)

						})
					})

					document.getElementById('tab2').addEventListener('click', e => {
						// 点击电缆段定位并且显示详情
						const target = e.target
						const id = target.id
						this.locateCableSection(id)
						this.showSelectedFeatureProperties(id)
					})
				});
				map.on('preclick', (e) => {
					this.clearHighlight()
				})
				map.on('click', e => {
					// 如果有通道和电缆重叠在一起，就只选择通道
					const features = map.queryRenderedFeatures(e.point);
					if (features.length === 0) {
						return;
					}
					console.log('selected features:', features)
					let topFeature = features[0]

					for (let i = 0; i < features.length; i++) {
						const f = features[i];
						if (f.source === "cableSection") {
							// 如果选中了电缆段，跳过
							continue
						} else {
							topFeature = features[i]
							break
						}
					}

					if (topFeature && topFeature.id) { // 判断是不是加载的geojson图层，mapbox自带的图层没有id字段
						const topLayer = topFeature.layer.id
						if (topLayer.indexOf('label') > -1) {
							// 只点label不高亮
							return
						}

						const equipmentType = topLayer.split('-')[1]
						let alreadyHighlightedFeatures = highlightSubstationLine.equipments[equipmentType] || []

						map.setFilter(topLayer + '-highlighted', [
							'in',
							"id",
							...alreadyHighlightedFeatures,
							topFeature.id
						]);

						const source = topFeature.source
						const selectedStateId = topFeature.id;
						console.log('读取到点击的电缆井id:', selectedStateId)
						selectedFeature = {
							source: source,
							id: selectedStateId
						}
						console.log('highlight feature:', selectedFeature)
						map.setFeatureState(selectedFeature, {
							active: true
						});
						this.ownerinstance.callMethod('fetchHeadName', selectedStateId)
						this.showSelectedFeatureProperties(selectedStateId, topLayer)
					}
				})

				const addresses = document.getElementsByClassName("address")
				for (const el of addresses) {
					el.onclick = () => {
						const {
							coordinates,
							des,
							type
						} = navigationData
						if (!coordinates || !des || !type) {
							alert('缺少定位需要的数据')
						} else {
							this.showToast('正在启动定位服务', 1000);
							plus.geolocation.getCurrentPosition((res) => {
								let latitude = res.coords.latitude;
								let longitude = res.coords.longitude;
								let dst = new plus.maps.Point(coordinates[0], coordinates[1]); //导航目的地
								let src = new plus.maps.Point(latitude, longitude); //导航起始地
								plus.maps.openSysMap(dst, des, src)
								this.hideToast()
								this.showToast('正在启动导航软件，请稍候...', 5000);
							}, function() {
								alert('请开启定位！')
							});
						};
					}
				}

				
				document.getElementById('button-cancel-highlight-route').onclick = (e) => {
					highlightSubstationLine.id = ''
					highlightSubstationLine.equipments = {}
					this.clearHighlight()
					e.target.style.zIndex = -1
				}
			}
		}
	}
</script>

<style lang="scss">
	@import '@/style/config.scss';

	//设备树
	// .title {
	// 	font-size: 0.8rem;
	// 	font-weight: bold;
	// 	background: #7ab6bf;
	// 	color: #fff;
	// 	padding: 10px;
	// 	// margin-top: 1rem;
	// }
	body {
		width: 100%;
		height: 100vh;
		overflow: hidden;
	}

	::v-deep .u-slide-left-enter-to {
		right: 20%;
		overflow: auto;
	}

	::v-deep .ly-tree {
		padding: 0;

		// .ly-tree-node__content {
		// 	height: 1.5rem;
		// }

		.ly-tree-node__icon {
			background-size: 100%;
		}

		.Home,
		.Province,
		.City,
		.Area {
			background-image: url('/static/tuli/area.svg');
		}

		.substation {
			background-image: url('/static/tuli/substation.svg');
		}

		.substationLine {
			background-image: url('/static/tuli/substationLine.svg');
		}

		.cableSection {
			background-image: url('/static/tuli/cableSection.svg');
		}

		.equipment {
			background-image: url('/static/tuli/equipment.svg');
		}

		.transformer {
			background-image: url('/static/tuli/transformer.png');
		}

		.branchBox {
			background-image: url('/static/tuli/branchBox.png');
		}

		.ringBox {
			background-image: url('/static/tuli/ringBox.png');
		}

		.tower {
			background-image: url('/static/tuli/tower.png');
		}

		.steeltower {
			background-image: url('/static/tuli/steeltower.png');
		}

		.cementtower {
			background-image: url('/static/tuli/cementtower.png');
		}

		.woodtower {
			background-image: url('/static/tuli/woodtower.png');
		}

		.unknowtower {
			background-image: url('/static/tuli/unknowtower.png');
		}

		.switchStation {
			background-image: url('/static/tuli/switchStation.png');
		}

		.electricityRoom {
			background-image: url('/static/tuli/electricityRoom.png');
		}

		.compactSubstation {
			background-image: url('/static/tuli/compactSubstation.png');
		}

		.virtual {
			background-image: url('/static/tuli/virtual.png');
		}

		.DlWay-fix,
		.DlWay,
		.road {
			background-image: url('/static/tuli/road.svg');
		}

		.cableWell {
			background-image: url('/static/tuli/cableWell.png');
		}

		.RegCableWell {
			background-image: url('/static/tuli/regcablewell.png');
		}

		.UnknowCableWell {
			background-image: url('/static/tuli/unknowcablewell.png');
		}

		.visulCableWell {
			background-image: url('/static/tuli/virtual.png');
		}

		.YhCableWell {
			background-image: url('/static/tuli/yhjmap.png');
		}

		.cableConnector {
			background-image: url('/static/tuli/cableConnector.svg');
		}

		.channel {
			background-image: url('/static/tuli/channel.svg');
		}

		.Other {
			background-image: url('/static/tuli/Other.svg');
		}

		.turnPoint {
			background-image: url('/static/tuli/TurnPoint.svg');
		}
	}

	.map-wrap {
		width: 100vw;
		height: 100vh;
		overflow: hidden;
	}

	.topbar {
		position: absolute;
		top: 3rem;
		left: 0.5rem;
		width: 100%;
		height: 40px;
		padding: 0.2rem;
		z-index: 10;
		display: flex;

		.check-equipment {
			width: 30px;
			height: 30px;
			background-color: #fff;
			padding: 0.2rem;
			border-radius: 0.5rem;
			margin-right: 1rem;
		}

		.search-input {
			width: 17rem;
			position: relative;
		}

		.search {
			height: 2.5rem;
		}

		.search-result {
			position: absolute;
			top: 2.5rem;
			background: #fff;
			width: 100%;
			height: auto;
			padding: 0.5rem 0;
		}

		.u-list-item-cell {
			padding: 0.4rem 0.5rem;
		}

		.empty-result {
			text-align: center;
			padding: 1rem;
		}
	}

	#map-box {
		top: 0;
		left: 0;
		bottom: 50px;
		right: 0;
		position: absolute;
		background-color: #ffffff;
	}

	#map-box /deep/ .mapboxgl-ctrl-geocoder {
		min-width: 140px;
	}

	#map-box /deep/ .mapboxgl-ctrl-geocoder input[type='text'] {
		height: 30px;
	}

	#map-box /deep/ .mapboxgl-ctrl-geocoder .geocoder-icon-search {
		top: 5px;
	}

	#map-box /deep/ .mapboxgl-ctrl-geocoder .geocoder-pin-right * {
		top: 5px;
	}

	.control-box {
		padding: 10rpx 30rpx;
		background-color: #00aaff;
		position: absolute;
		right: 0;
		top: 0;
		z-index: 999px;
	}

	.deepTo {
		color: rgba(0, 0, 0, 0.6);
		background-color: #dedede;
		margin-top: 10px;
		margin-bottom: 10px;
		display: inline-block;
		line-height: 2.3;
		font-size: 13px;
		padding: 0 1.34em;
		border-radius: 5px;
		cursor: pointer;
	}

	.address {
		margin-left: 8px;
		color: '#55aa00';
		font-weight: 500;
		color: red;
	}

	.properties-panel {
		position: absolute;
		border-bottom: 1px solid #dddddd;
		bottom: 6vh;
		width: 100%;
		height: 13rem;
		background-color: #ffffff;
		color: #333333;
		font-size: 14px;
		overflow: auto;
		z-index: -1;

		.title {
			line-height: 30px;
			margin-left: 8px;
		}
	}

	.properties-table,
	.properties-table tr,
	.properties-table tr td {
		border: 1px solid #dfdfdf;
	}

	.properties-table {
		width: 100%;
		border-collapse: collapse;

		tr:nth-child(odd) {
			background-color: #f6f9fa;
		}
	}

	#channel-panel,
	#cable-well-panel {
		position: absolute;
		border-bottom: 1px solid #dddddd;
		bottom: 6vh;
		width: 100%;
		height: 13rem;
		z-index: 100;
		background-color: #ffffff;
		color: #333333;
		font-size: 14px;
		overflow: auto;
		z-index: -1;
	}

	#cable-well-panel {
		bottom: 5.9vh;
		width: 100%;
		height: 15rem;
	}

	.cable-well-panel-title {
		line-height: 2rem;
		border-bottom: 1px solid #dddddd;
	}

	#channel-panel.hide {
		z-index: -1;
	}

	#channel-panel.show {
		z-index: 99;
	}

	.tab-header {
		display: flex;
		width: 100%;
		border-bottom: 1px solid #dddddd;

		.tab-header-item {
			width: 50%;
			text-align: center;
			padding: 0.5rem;

			&.active {
				background: #00bfbf;
			}

			a {
				text-decoration: none;
				display: block;
				color: #333333;
			}
		}
	}

	.panes-container {
		position: absolute;
		height: 10.8rem;
		width: 100%;
	}

	.table-container {
		height: 11.1rem;
		width: 100%;
		overflow: auto;
	}

	.tab-pane {
		background-color: #fff;
		position: absolute;
		height: 100%;
		width: 100%;
		top: 0;
		z-index: 0;
		overflow: auto;

		.select-style {
			width: 100%;
			height: 80rpx;
			display: flex;
			align-items: center;

			.picker-content {
				width: 400rpx;
				font-size: 30rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				border: 1rpx solid #ccc;
				/* 外边框样式 */
				border-radius: 5rpx;
				/* 圆角边框（可选） */

			}

			text {
				padding-left: 20rpx;
			}
		}

		.temperature-item {
			width: 100%;
			flex: 1;
			/* 每个项占一半 */
			display: flex;
			flex-direction: row;
			justify-content: center;
			padding: 30rpx 0 30rpx 0;
			border-left: 1px solid #ccc;
			/* 左边框 */
			border-right: 1px solid #ccc;
			/* 右边框 */
			border-bottom: 1px solid #ccc;
			/* 底部边框 */
			/* 灰色边框 */
			position: relative;

			/* 相对定位以支持伪元素 */
			.row {
				display: flex;
				align-items: center;
				width: 50%;
				height: 30rpx;
				padding-left: 20rpx;

				.lable {
					text-align: left;
				}
			}
		}

		.temperature-item-one {
			width: 100%;
			flex: 1;
			/* 每个项占一半 */
			display: flex;
			flex-direction: row;
			justify-content: center;
			padding: 30rpx 0 30rpx 0;
			border: 1px solid #ccc;
			position: relative;

			/* 相对定位以支持伪元素 */
			.row {
				display: flex;
				align-items: center;
				width: 50%;
				height: 30rpx;
				padding-left: 20rpx;

				.lable {
					text-align: left;
				}
			}
		}

		.temperature-item-one::after {
			content: '';
			position: absolute;
			top: 0;
			left: 50%;
			/* 中间位置 */
			width: 1px;
			/* 边框宽度 */
			height: 100%;
			/* 边框高度 */
			background-color: #ccc;
			/* 边框颜色 */
			transform: translateX(-50%);
			/* 中心对齐 */
		}

		.temperature-item::after {
			content: '';
			position: absolute;
			top: 0;
			left: 50%;
			/* 中间位置 */
			width: 1px;
			/* 边框宽度 */
			height: 100%;
			/* 边框高度 */
			background-color: #ccc;
			/* 边框颜色 */
			transform: translateX(-50%);
			/* 中心对齐 */
		}

		.temperature-item:last-child {
			margin-right: 0;
			/* 最后一个项无右间距 */
		}


		&.active {
			z-index: 1;
		}

		.cable-list-item {
			padding: 0.5rem 0.2rem;
			line-height: 1.5rem;
			border-bottom: #d7d7d7;
		}

		.cable-list-item:nth-child(2n) {
			background-color: #f7f7f7;
		}
	}

	.cable-connector-title {
		line-height: 3rem;
		padding-left: 2rem;
	}

	#toast {
		position: absolute;
		padding: 0.5rem;
		top: 50%;
		left: 50%;
		transform: translate(-50%, 0);
		background: #333333;
		opacity: 0.7;
		height: auto;
		width: 60%;
		color: #ffffff;
		text-align: center;
		border-radius: 0.2rem;
		z-index: -2;
	}

	#control-legend {
		position: absolute;
		top: 50%;
		transform: translate(0, -50%);
		width: 100%;
		text-align: center;
		z-index: -1;

		.control-legend-content {
			margin: 15%;
			background-color: #ffffff;
			padding: 1rem;
			overflow: hidden;
		}

		.title {
			text-align: left;
			margin: 1rem 0;
		}

		img {
			width: 100%;
		}
	}

	.mapboxgl-control-container {
		z-index: 102; // 让控件处于最上层
	}

	.mapboxgl-ctrl-top-right {
		margin-top: 6rem;
	}

	.mapbox-gl-control-basemap {
		background: url("data:image/svg+xml,%3Csvg width='29' height='29' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg' %3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M12.447 4.106a1 1 0 0 0-.894 0l-9 4.5a1 1 0 0 0 0 1.788l9 4.5a1 1 0 0 0 .894 0l9-4.5a1 1 0 0 0 0-1.788l-9-4.5zM12 12.882L5.236 9.5 12 6.118 18.764 9.5 12 12.882z'/%3E%3Cpath d='M3.447 13.606a1 1 0 1 0-.894 1.788l9 4.5a1 1 0 0 0 .894 0l9-4.5a1 1 0 1 0-.894-1.788L12 17.882l-8.553-4.276z'/%3E%3C/svg%3E") no-repeat center;
		background-repeat: no-repeat;
		background-position: 50%;
		background-size: 80%;
	}

	.mapbox-gl-control-legend {
		background: url("data:image/svg+xml,%3Csvg class='icon' viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg' width='200' height='200'%3E%3Cpath d='M334.016 727.04a32 32 0 1 0 0-64 32 32 0 0 0 0 64zm0-183.04a32 32 0 1 0 0-64 32 32 0 0 0 0 64zm0-182.016a32 32 0 1 0 0-64 32 32 0 0 0 0 64zm478.976-279.04H211.008c-37.568.064-67.968 30.528-68.032 68.032v722.048c.064 37.504 30.464 67.968 68.032 67.968h601.984c37.568 0 67.968-30.464 68.032-67.968V150.976c-.064-37.504-30.464-67.968-68.032-67.968zm-3.968 786.048H214.976V155.008h594.048v713.984zM414.016 296h307.968c5.376 0 8 2.688 8 8v48c0 5.312-2.624 8-8 8H414.08c-5.376 0-8-2.688-8-8v-48c0-5.312 2.624-8 8-8zm0 184h307.968c5.376 0 8 2.688 8 8v48c0 5.312-2.624 8-8 8H414.08c-5.376 0-8-2.688-8-8v-48c0-5.312 2.624-8 8-8zm0 184h307.968c5.376 0 8 2.688 8 8v48c0 5.312-2.624 8-8 8H414.08c-5.376 0-8-2.688-8-8v-48c0-5.312 2.624-8 8-8z'/%3E%3C/svg%3E") no-repeat center;
		background-position: 50%;
		background-size: 80%;
	}

	#basemap-switch-panel {
		position: absolute;
		bottom: -12rem;
		width: 100%;
		height: 12rem;
		z-index: 103;
		background: #ffffff;
		border-top-left-radius: 1rem;
		border-top-right-radius: 1rem;
		transition: bottom 0.5s;

		.title {
			margin: 0.5rem 1rem 1rem;
			font-size: 1.1rem;
			font-weight: 500;
		}

		.basemap-container {
			display: flex;
			justify-content: space-around;

			.basemap-item {
				text-align: center;

				.thumbnail {
					width: 8rem;
					height: 4rem;
					margin: 0.6rem 0;
					padding: 0;
					border-radius: 0.5rem;
					border: 1pt solid #ffffff;
				}

				&.active {
					.thumbnail {
						border: 1pt solid #00aaff;
					}
				}
			}
		}
	}

	#button-cancel-highlight-route {
		position: absolute;
		padding: 0.5rem;
		top: 6rem;
		left: 0.5rem;
		z-index: -1;
		border: 1pt solid #999999;
		border-radius: 0.3rem;
		background: #cfe4fa;
	}

	#connector-list {
		background-color: #ffffff;
		height: 100%;

		.connector-list-container>* {
			padding: 0.8rem 0.2rem;
		}
	}

	#connector-detail-pane {
		position: absolute;
		z-index: -1;
		top: 0;
		width: 100%;
		height: 100%;
		background-color: #ffffff;
		display: none;

		&.active {
			z-index: 2;
			display: block;
		}

		#back-to-list {
			margin: 0.5rem 0.1rem;
			color: #00aaff;
		}
	}
	
	
	// .mapboxgl-ctrl {
	//     display: none !important;
	// }
	// //或隐藏不了
	// //加入/deep/
	// /deep/.mapboxgl-ctrl {
	//     display: none !important;
	// }

</style>